package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mapper.ChatMessageMapper;
import com.demo.pojo.ChatMessage;
import com.demo.pojo.ResultVO;
import com.demo.service.ChatMessageService;
import com.demo.utils.CurrentHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    /**
     * 发送消息
     * @param chatMessage
     * @return
     */
    @Override
    public ResultVO send(ChatMessage chatMessage) {
        chatMessage.setTime(LocalDateTime.now());
        chatMessage.setFromId(CurrentHolder.getCurrentId());
        chatMessage.setId(null);
        chatMessage.setStatus(0);
        boolean save = this.save(chatMessage);
        if (!save) {
            throw new RuntimeException("发送消息失败");
        }
        return ResultVO.success();
    }

    /**
     * 根据id获取消息
     * @param id
     * @return
     */
    @Override
    public ResultVO<List<ChatMessage>> get(Long id) {
        Long currentId = CurrentHolder.getCurrentId();
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_id", currentId)
                .eq("to_id", id)
                .or()
                .eq("from_id", id)
                .eq("to_id", currentId)
                .orderByDesc("time");
        List<ChatMessage> chatMessages = this.list(queryWrapper);


        return ResultVO.success(chatMessages);
    }
}
